import {Component, Input, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {ActivatedRoute, Params, Router} from "@angular/router";
import {AuthService} from "@shared/service/auth/auth.service";
import {ToolsService} from "@shared/service/tools/tools.service";
import {SeedInfiniteScroll} from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import {Subject} from "rxjs/Rx";
import {EventsService} from "@core/events/events.service";
import {CouponRespVO} from "@interface/index";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {ValidationService} from "@shared/service/validator/validator.service";
import {GoodsTicketService} from "@goods/goods-ticket/goods-ticket.service";
import {TicketSkuDetailVO} from "../../../../interface/goods/goods.model";


@Component({
  selector: 'seed-goods-ticket-order',
  templateUrl: 'goods-ticket-order.component.html',
  styleUrls: ['goods-ticket-order.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class GoodsTicketOrderComponent implements OnInit {
  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  @Input() markType; // 优惠券
  public skuCode: string;
  public goodsCode: string;
  public num: number;
  public ticketTypes: Array<any> = [];
  public ticketsForm: FormGroup;
  public ticketInfo = false;
  public ticketAddress = false;
  public ticketNum: string;
  public ticketPrice: number;
  public obtainType;
  public ticketSkuDetail: TicketSkuDetailVO;
  public ngUnsubscribe: Subject<void> = new Subject<void>();
  public usableCouponList: Array<CouponRespVO> = []; // 可用优惠券列表
  public couponCodeId: number; // 优惠券ID
  public totalPrice: number;  // 实际付款金额(减去优惠劵)
  public choose = false; // 是否已选择优惠劵
  public couponValue: number; // 优惠券金额
  public address: string;
  public params = { // 可用优惠券信息
    totalAmount: 0,
    page: 1,
    rows: 200,
  };
  public couponTotal: number;
  public cardChooseIndex: number;

  constructor(
    public authService: AuthService,
    private route: ActivatedRoute,
    public router: Router,
    public events: EventsService,
    private goodsTicketService: GoodsTicketService,
    public toolsService: ToolsService,
    private formBuilder: FormBuilder
  ) {
    this.route.queryParams
      .subscribe((param: Params) => {
        this.skuCode = param['skuCode'];
        this.num = param['num'];
        this.getTicketSkuDetail();
        this.getUsableCouponList();
      });
  }

  // 表单初始化
  createFormBuilder() {
    this.ticketsForm  = this.formBuilder.group({
      'name': ['', [Validators.required, Validators.minLength(2), Validators.maxLength(25)]],
      'phone': ['', [Validators.required, Validators.maxLength(11), ValidationService.accountValidator]],
      'obtainType': ['', [Validators.required]]
    });
  }

  // 取票方式
  ticketChange(val) {
    if (val) {
      this.ticketInfo = true;
      if (val === '比赛当天现场取票') {
        this.ticketNum = '471111';
        this.ticketAddress = false;
        this.ticketsForm.removeControl('address');
        this.ticketsForm.controls['obtainType'].setValue(val);
      } else if (val === '官方售票点取票') {
        this.ticketNum = '471112';
        this.ticketAddress = false;
        this.ticketsForm.removeControl('address');
      } else if (val === '邮寄门票(价格含邮费)') {
        this.ticketNum = '471113';
        this.ticketAddress = true;
        this.ticketsForm.addControl('address', new FormControl('', Validators.required));
      }
      if (this.ticketSkuDetail.ticket.needIdNo === true) {
        this.ticketsForm.addControl('ID', new FormControl('', ValidationService.IDnumValidator));
        this.ticketsForm.controls['obtainType'].setValue(val);
      }
    }
  }

  /**
   * @description 确认订单的订单详情
   * @author @zhoukfu1349
   * @date  2018-04-08
   * @param skuCode
   */
  getTicketSkuDetail() {
    const skuCode = this.skuCode;
    this.goodsTicketService.getTicketSkuDetail(skuCode)
      .subscribe((res) => {
        if (res.data) {
          this.ticketSkuDetail = res.data;
          this.ticketPrice = this.ticketSkuDetail.price;
          this.ticketTypes = [...this.ticketSkuDetail.ticket.obtainTypes];
        }
      });
  }


  /**
   * @description 可用优惠券列表
   * @author @zhoukf1349
   * @date 2018-04-08
   * @param param { totalAmount ， page , rows }
   */
  getUsableCouponList() {
    this.goodsTicketService.getUsableCouponList(this.params)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data && res.data.list.length > 0) {
        this.couponTotal = res.data.total;
        this.usableCouponList = [...this.usableCouponList, ...res.data.list];
      }
    });
  }

  /**
   * @description 选择优惠券
   * @author @zhupw1360
   * @date 2018-01-05
   * @param params { codeId ， couponValue , index }
   */
  chooseCoupon(codeId: number, couponValue: number, index: number) {
    this.choose = true;
    this.couponCodeId = codeId;
    this.couponValue = couponValue;
    this.totalPrice = this.ticketSkuDetail.price - couponValue;
    if (this.totalPrice < 0) {
      this.totalPrice = 0;
    }
    this.cardChooseIndex = index;
    this.events.publish('modal:close');
  }

  // 跳转优惠券说明
  goToCouponExplain() {
    this.router.navigate(['/goods/coupon/explain']);
  }

  /**
   * @description 提交下单(status=1:普通商品，直接去支付页，status=9：是赛事或票务，跳到分类接口，status=2：免费普通商品，直接跳到结果页，不用支付）
   * @author @zhoukf1349
   * @date  2018-04-09
   * @constructor
   */
  postSubmitTicket() {
    const formData = this.ticketsForm.controls;
    console.log(formData);
    const data = {
      name: formData['name'].value, // 收货人
      mobile: formData['phone'].value, // 收货人手机号
      idNo: formData['ID'] ? formData['ID'].value : '',
      address: formData['address'] ? formData['address'].value : '', // 详细地址
      obtainType: this.ticketNum,
      skuCode: this.skuCode,
      quantity: this.num
    };
    this.goodsTicketService.postTicketOrder(data).subscribe((res) => {
      if (res.result === '0') {
        if (this.ticketPrice === 0) {
          this.router.navigate(['/payment/result'], {queryParams: {mchOrderNumber: res.data.orderNumber}});
        } else {
          this.router.navigate(['/payment/'], {queryParams: {orderNumber: res.data.orderNumber}});
        }
      } else {
        this.toolsService.showToast(res.msg);
      }
    });
  }


  ngOnInit() {
    this.createFormBuilder();
    this.getTicketSkuDetail();
  }

}
